<template>
  <div class="systemAgent components-container">
	<!--=========头部=========-->
	<div class="searchBar">
	  <fns-header @search="queryList">
		<span slot="slot1">
			<el-form-item label="登录名">
			  <el-input v-model="header.userName" :maxlength="30" placeholder="请输入登录名" @keyup.enter.native="queryList" clearable></el-input>
			</el-form-item>
			<el-form-item label="姓名">
			  <el-input v-model="header.realName" :maxlength="30" placeholder="请输入姓名" @keyup.enter.native="queryList" clearable></el-input>
			</el-form-item>
		   <el-form-item label="状态">
			  <el-select v-model="header.status" placeholder="请选择状态" @keyup.enter.native="queryList" clearable>
				<el-option
				  v-for="item in stateOption"
				  :key="item.value"
				  :label="item.label"
				  :value="item.value">
				</el-option>
			  </el-select>
			</el-form-item>
		</span>
	  </fns-header>
  	</div>
	<!--=======表格=======-->
	<div class="fns-table-handle mainTable">
	  <div class="btnLine">
		<el-button type="primary" size="medium" icon="iconfont icon-xinzeng" @click="updateAndAdd('', 'add')" v-has="'pcadmin_sys_sys_user_create'"> 新增</el-button>
	  </div>
	  <fns-table :customerField="customerField">
		<el-table-column
				slot="right"
				label="操作"
				align="center"
				fixed="right"
				width="100">
		  <template slot-scope="scope" class="smallIcon">
		  	<el-tooltip content="查看" placement="top"  v-has="'pcadmin_sys_sys_user_detail'">
			  <el-button type="mini" icon="iconfont icon-chakan3" @click="updateAndAdd(scope, 'look')"></el-button>
			</el-tooltip>
			<el-tooltip content="修改" placement="top"  v-has="'pcadmin_sys_sys_user_update'">
			  <el-button type="mini" icon="iconfont icon-xiugai" @click="updateAndAdd(scope, 'update')"></el-button>
			</el-tooltip>
		  </template>
		</el-table-column>
	  </fns-table>


	<!-- ========页码======-->
	<pages v-on:_pageChange="_pageChange" :total="total" :currentPage="page.index"></pages>
	</div>
	<!--=======新增/修改/查看弹窗=======-->
	<div v-if="dialogData.dialogVisible">
	  <fns-dialog :dialogData="dialogData" @submitForm="submitForm" width="100%">
		<el-form  id='formModel' ref="formModel" :model="formModel" :rules="rules" slot="body" v-loading="loading">
		  <el-row>
			  <el-form-item v-if="isUserName" label="登录名">
				<el-input v-model="formModel.userName" type="text" placeholder="请输入登录名"  disabled></el-input>
			  </el-form-item>
			  <el-form-item v-else label="登录名" :prop="isValidate ? 'userName' : ''" >
				<el-input v-model="formModel.userName" :minlength="4" :maxlength="16" type="text" placeholder="请输入登录名" :clearable="isValidate ? true : false" :disabled="isValidate ? false : true"></el-input>
			  </el-form-item>

			  <el-form-item :offset="1" label="姓名" :prop="isValidate ? 'realName' : ''">
				<el-input v-model="formModel.realName" :maxlength="20" type="text" placeholder="请输入姓名" :clearable="isValidate ? true : false" :disabled="isValidate ? false : true"></el-input>
			  </el-form-item>
		  </el-row>
		  <el-row>
			  <el-form-item label="密码" :prop="isValidate ? 'password': ''">
				<el-input v-model="formModel.password" :minlength="6" :maxlength="16" type="password" placeholder="请输入密码" :clearable="isValidate ? true : false" :disabled="isValidate ? false : true"></el-input>
			  </el-form-item>

			  <el-form-item :offset="1" label="确认密码" :prop="isValidate ? 'confirmPsd' : ''">
				<el-input v-model="formModel.confirmPsd"  :minlength="6" :maxlength="16" type="password" placeholder="请再次输入密码" :clearable="isValidate ? true : false" :disabled="isValidate ? false : true"></el-input>
			  </el-form-item>
		  </el-row>
		  <el-row>
			  <el-form-item label="手机号" :prop="isValidate ? 'phoneNum' : ''">
				<el-input v-model="formModel.phoneNum" :minlength="11" :maxlength="11" type="text" placeholder="请输入正确的手机号" :clearable="isValidate ? true : false" :disabled="isValidate ? false : true"></el-input>
			  </el-form-item>

			  <el-form-item :offset="1" label="状态" :prop="isValidate ? 'status' : ''">
				<el-radio-group v-model="formModel.status" :disabled="isValidate ? false : true" >
				  <div v-if="isValidate === true">
					<el-radio :label="1">启用</el-radio>
					<el-radio :label="0">停用</el-radio>
				  </div>
				  <div v-else>
					<el-radio :label="1">启用</el-radio>
					<el-radio :label="0">停用</el-radio>
				  </div>
				</el-radio-group>
			  </el-form-item>
		  </el-row>
		  <el-row>
			  <el-form-item label="所属角色" class="wid-md" :prop="isValidate ? 'roleIds' : ''">
				<el-select v-model="formModel.roleIds" multiple filterable placeholder="请选择角色" :clearable="isValidate ? true : false" :disabled="isValidate ? false : true" style="width: 100%;">
				  <el-option
						  v-for="(item, index) in rolesOptions"
						  :key="index"
						  :label="item.value"
						  :value="item.key">
				  </el-option>
				</el-select>
			  </el-form-item>
		  </el-row>
		</el-form>
	  </fns-dialog>
	</div>

  </div>
</template>

<script>
  import { formaterTableData, initScrollTop, clearForm } from '@/utils/publicMethod'
  import * as api from '@/api/system/userMng'
  import * as api2 from '@/api/selected'
  import pages from '@/components/common/page' // 分页
  import fnsHeader from '@/components/common/header' // 头部
  import fnsDialog from '@/components/common/dialog' // lg 780px弹窗
  import fnsTable from '@/components/common/table' // 表格
  import * as validate from '@/utils/validate' // 验证
  import { mapState } from 'vuex'

  export default {
  name: 'User',
	data() {
	  var confirmPsd = (rule, value, callback) =>{
		if (value !== this.formModel.password) {
		  callback(new Error('输入密码不一致!'));
		} else {
		  callback()
		}
	  };
	  var psd = (rule, value, callback) =>{
		if (this.formModel.confirmPsd !== '') {
		  this.$refs['formModel'].validateField('confirmPsd');
		}
		callback()
	  };
	  return {
		loading: false,
		total: 0,
		isUserName: false,
		isValidate: false,
		header: { // 头部
		  userName: '',
		  realName: '',
		  status: ''
		},
		page: {
		  index: 1,
		  size: 10
		},
		rolesOptions: [],
		dialogData: { // 弹窗
		  title: '',
		  dialogVisible: false,
		  size: 'md', // lg, md , sm
		  btnLeft: '取 消',
		  btnRight: '提 交',
		  showBackBtn: false
		},
		customerField: { // 自定义表格字段
		  tableData: [],
		  loading: false,
		  allField: [
			{
			  label: '序号',
			  align: 'center',
			  type: 'index',
			  width: '80'
			 },
			{
			  prop: 'userName',
			  label: '登录名',
			  align: 'center'
			},
			{
			  prop: 'realName',
			  label: '姓名',
			  align: 'center'
			},
			{
			  prop: 'phoneNum',
			  label: '手机号',
			  align: 'center'
			},
			{
			  prop: 'roleNames',
			  label: '角色',
			  align: 'center',
			  formatter: this.formatterRole
			},
			{
			  prop: 'status',
			  label: '状态',
			  formatter: this.formatterStatus,
			  align: 'center'
			},
			{
			  prop: 'createdOn',
			  label: '创建时间',
			  align: 'center'
			}
		  ]
		},
		formModel: {
		  userName: '',
		  realName: '',
		  password: '',
		  phoneNum: '',
		  status: 1,
		  roleIds: []
		},
		tableData: [],
		rules: {
		  userName: [
		  	validate.userName,
			validate.blur()
		  ],
		  realName: [
		  	validate.noSpace,
			validate.blur()
		  ],
		  password: [
			validate.blur(),
			validate.psd,
			{ validator: psd, trigger: 'blur' },
		  ],
		  confirmPsd: [
			validate.blur(),
			validate.psd,
			{ validator: confirmPsd, trigger: 'blur' },
		  ],
		  phoneNum: [
			validate.blur(),
			validate.phone
		  ],
		  roleIds: [
			validate.change()
		  ],
		}
	  }
	},
	components: {
	  pages,
	  fnsHeader,
	  fnsTable,
	  fnsDialog
	},
	watch: {
	  ['dialogData.dialogVisible'] (val) {
		if (!val) {
		  if (this.$refs['formModel'] !== undefined) { // 重置表单及移除验证
			this.$refs['formModel'].resetFields()
		  }
		}
	  }
	},
	created() {
	  this.queryList()
	},
	computed: {
	  ...mapState({
		stateOption: state => state.selected.state
	  })
	},
	mounted() {
//		this.queryList()
	},
	methods: {
	  _pageChange(val, flag) {
		var arr = []
		if (flag === 'size') {
		  this.page.index = val
		  this.queryList('page')
		} else {
		  arr.push(val)
		  this.page.index = 1
		  this.page.size = arr[0]
		  this.queryList('page')
		}
	  },
	  // 打开弹窗
	  updateAndAdd(res, name) {
		this.dialogData.title =  name === 'add' ? '新增用户' :  name === 'update' ? '修改用户' : name === 'look' ? '查看用户信息' : '';
		this.dialogData.dialogVisible = true;
		let id = res ? res.row.id : '';
		this.id = id
		initScrollTop('formModel') // 滚动条top=0
		if ( name === 'add') {
		  clearForm(this.formModel); // 清空数据
		  this.formModel.status = 1
		  this.dialogData.showBackBtn = false;
		  this.isValidate = true
		  this.isUserName = false
		  api2.roleList().then((res) => {
			this.rolesOptions = res.data
		  })
		} else if (name === 'update') { // 修改
		  this.dialogData.showBackBtn = false;
		  this.isValidate = true // 是否验证
		  this.isUserName = true
		  this.look(id)
		  api2.roleList().then((res) => {
			this.rolesOptions = res.data
		  })
		} else {
		  this.dialogData.showBackBtn = true;
		  this.dialogData.btnLeft = '返 回'
		  this.isValidate = false // 是否验证
		  this.isUserName = false
		  this.look(id)
		}
	  },
//	  search() {
//		this.page.index = 1
//		this.queryList()
//	  },
	  add() {
		delete this.formModel.confirmPsd
		delete this.formModel.id
		this.dialogData.dialogVisible = true
		api.addUser(this.formModel).then((res) => {
		  if(+res.code === 0) {
			this.dialogData.dialogVisible = false
			this.queryList()
		  } else {
			this.formModel.confirmPsd = this.formModel.password
		  }
		}).catch(() => {
		  this.formModel.confirmPsd = this.formModel.password
		})
	  },
	  look(id) {
	  	this.loading = true
		api.lookUser(id).then((res) => {
		  if(+res.code === 0) {
			var rowData = res.data
			this.formModel = { ...res.data };
			this.formModel.id = rowData.id || ''
			this.formModel.userName = rowData.userName || ''
			this.formModel.realName = rowData.realName || ''
			this.formModel.phoneNum = rowData.phoneNum || ''
			this.formModel.roleIds = rowData.roleIds || []
			this.formModel.status = Number(rowData.status || '')
			this.formModel.password = this.formModel.confirmPsd = '1@059x'
			if (this.$refs['formModel'] !== undefined) { // 重置表单及移除验证
			  this.$refs['formModel'].resetFields()
			}
		  }
		  this.loading = false
		})
	  },
	  updateEvent() {
		delete this.formModel.confirmPsd
		delete this.formModel.userName
		delete this.formModel.id
		this.dialogData.dialogVisible = true
		api.updateUser(this.formModel, this.id).then((res) => {
		  if(+res.code === 0) {
			this.dialogData.dialogVisible = false
			this.queryList()
			this.search()
		  }
		  this.formModel.confirmPsd = this.formModel.password === '******' ? '1@059x' : this.formModel.password
		}).catch(() => {
		  this.formModel.confirmPsd = this.formModel.password === '******' ? '1@059x' : this.formModel.password
		})
	  },
	  submitForm(val) {
		if (val === '修改用户') {
		  this.$refs['formModel'].validate((valid) => {
			if (valid) {
			  if(this.formModel.password === '1@059x' || this.formModel.confirmPsd === '1@059x'){
//				this.formModel.password = '******'
//				this.formModel.confirmPsd = '******'
			  }
			  this.updateEvent()
			  this.queryList()
			}
		  })
		} else if (val === '新增用户') {
		  this.$refs['formModel'].validate((valid) => {
			console.log('add', valid)
			if (valid) {
			  this.add()
			  this.queryList()
			  this.page.index = 1
			}
		  })
		} else if (val === '查看用户信息') {
		  this.dialogData.dialogVisible = false
		}
	  },
	  queryList() {
		this.customerField.loading = true
		let pages = {
		  index: this.page.index,
		  size: this.page.size
		}
		let data = Object.assign({}, this.header, pages)
		api.userList(data).then((res) => {
		  // this.tableData = formaterTableData(res.data.rows) // 格式化表格数据
		  this.customerField.tableData = res.data.rows
		  this.total = +res.data.total
		  this.customerField.tableData.map((item, index) => {
			for (var i in item) {
			  if (item[i] === null || '') {
				item[i] = ' '
			  }
			}
		  })
		  this.customerField.loading = false
		}).catch(() => {
		  this.customerField.loading = false
		})
	  },
	  formatterStatus(row) {
		if(+row.status === 1) {
		  return '启用'
		} else {
		  return '停用'
		}
	  },
	  formatterRole(row) {
	  	if (row.roleNames.length !== 0) {
	  		 return row.roleNames.join("，")
	  	} else {
	  		return ''
	  	}
	  }
	}
  }
</script>
<style lang="scss">
  .systemAgent {
	.el-select__tags{flex-wrap:inherit;}
  }
</style>


